import { existsSync } from 'fs';
import inquirer from 'inquirer';
import * as path from 'path';
import config from '../config';
import { copyDirectory, deleteDirectory, executeCmd, getCliConfigData, isDirectoryEmpty, trimPath } from '../utils';

export default async function (projectPath: string) {
    projectPath = trimPath(projectPath);
    console.log('项目路径: ' + projectPath);
    if (!projectPath || !isDirectoryEmpty(projectPath)) throw '请输入空文件夹路径';

    const result = await inquirer.prompt<{ type: string }>([
        {
            name: 'type',
            type: 'list',
            message: '选择框架',
            default: config.types.Creator3D,
            // 目前只开放Creator3D
            choices: [config.types.Creator3D]
        }
    ], { type: config.types.Creator3D });

    // 模版临时目录
    const templatePath = path.join(__dirname, 'template');
    deleteDirectory(templatePath);

    // 下载源码
    const gitAddress = config.gits[result.type];
    console.log('拉取中: git clone ' + gitAddress);
    const code = await executeCmd('git', ['clone', '--depth=1', gitAddress, `"${templatePath}"`]);
    if (code != 0) {
        console.error('克隆失败, 检查git环境是否可用');
        return;
    }

    // 将模版拷贝至项目目录
    copyDirectory(templatePath, projectPath);
    deleteDirectory(templatePath);

    // 源cliconfig数据
    const cliconfig = getCliConfigData(projectPath);
    console.log(`创建成功，版本号: ${cliconfig.version}`);

    console.log('安装依赖中...');
    const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';
    await executeCmd(npm, ['install']);
    if (existsSync(path.join(projectPath, 'web-template'))) {
        await executeCmd(npm, ['--prefix', path.join(projectPath, 'web-template'), 'install']);
    }
}